<template>
  <div class="app-container check-list">
    <div class="filter-container">
      <el-select v-model="listQuery.lotid" :loading="lotLoading" clearable filterable placeholder="专场" @change="handleFilter">
        <el-option v-for="item in lots" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <!-- 卖家 -->
      <el-select v-if="roles.includes('editor') || (roles.includes('cashier') && routeName === 'SettleSend')" v-model="listQuery.send_user" :loading="userLoading" clearable filterable placeholder="送货人姓名或手机号" @change="handleFilter">
        <el-option v-for="item in sendUsers" :key="item.id" :label="item.label" :value="item.id" />
      </el-select>
      <!-- 买家 -->
      <el-select v-if="roles.includes('outer') || (roles.includes('cashier') && routeName === 'SettleBuy')" v-model="listQuery.buy_user" :loading="userLoading" clearable filterable placeholder="购买人姓名、号牌或手机号" @change="handleFilter">
        <el-option v-for="item in buyUsers" :key="item.id" :label="item.label" :value="item.id" />
      </el-select>
      <el-button type="primary" plain icon="el-icon-search" @click="handleFilter(true)">查询</el-button>

      <el-button v-permission="['editor']" type="primary" :disabled="checkList.length === 0" icon="el-icon-printer" @click="handleOneKeyPrint">
        一键打印
      </el-button>
      <el-button v-permission="['outer']" type="primary" :loading="outLoading" :disabled="checkList.length === 0" icon="el-icon-sold-out" @click="handleOneKeyOut">一键提货</el-button>
      <el-button v-if="routeName === 'SettleSend'" type="warning" :disabled="checkList.length === 0" icon="el-icon-shopping-bag-2" @click="handleCreateOrder({ type: 'send' })">一键创建订单</el-button>
      <el-button v-if="routeName === 'SettleBuy'" type="warning" :disabled="checkList.length === 0" icon="el-icon-shopping-bag-2" @click="handleCreateOrder({ type: 'buy' })">一键创建订单</el-button>
    </div>

    <goods-table
      v-if="listQuery.lotid && (listQuery.send_user || listQuery.buy_user)"
      :list-loading="listLoading"
      :list-data="list"
      :empty-text="emptyText"
      multi-select
      @update="fetchData"
      @settle="handleCreateOrder"
      @checkChange="handleCheckChange"
    />

    <el-alert v-else title="请将查询条件补充完整" type="warning" :closable="false" />

    <div v-show="total > 0 && (listQuery.lotid && (listQuery.send_user || listQuery.buy_user))" class="pagination-container">
      <el-pagination background :current-page="listQuery.page" layout="total" :total="total" />
    </div>

    <el-dialog title="创建订单" width="60%" :visible.sync="dialogSettleVisible">
      <order-table ref="order-table" :type="routeName === 'SettleSend' ? 'send' : 'buy'" :goods-list="settleData" />
      <br><br>
      <el-form :model="orderForm" label-position="left" label-width="80px">
        <el-form-item label="其他费用">
          <el-input v-model.trim="orderForm.other_fee" type="number" />
        </el-form-item>
        <el-form-item label="合计费用">
          <el-input v-model="orderTotalFee" type="number" disabled />
        </el-form-item>
        <el-form-item label="转账银行">
          <el-input v-model.trim="orderForm.bankname" />
        </el-form-item>
        <el-form-item label="银行卡号">
          <el-input v-model.trim="orderForm.bankcard" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model.trim="orderForm.address" type="textarea" :autosize="{ minRows: 1, maxRows: 2}" />
        </el-form-item>
        <el-form-item label="订单备注">
          <el-input v-model.trim="orderForm.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogSettleVisible = false">取 消</el-button>
        <el-button :loading="settleLoading" type="primary" @click="submitOrder">创建订单</el-button>
      </div>
    </el-dialog>

    <el-dialog class="print-dialog" fullscreen center :visible.sync="dialogPrintVisible">
      <div id="printContent">
        <print-table :title="printData.title" :type="printData.type" :info="printData.info" :list="printData.list" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPrintVisible = false">关 闭</el-button>
        <el-button :loading="printLoading" type="primary" @click="doPrint">打 印</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Print from 'print-js'
import { toThousands } from '@/utils'
import GoodsTable from './components/GoodsTable'
import PrintTable from './components/PrintTable'
import OrderTable from './components/OrderTable'
import { getAllUsers } from '@/api/user'
import { getAllLots } from '@/api/lot'
import { getGoods, setGoodsStateMulti } from '@/api/goods'
import { getTaxRate, createOrder } from '@/api/order'

export default {
  components: { GoodsTable, PrintTable, OrderTable },
  data () {
    return {
      routeName: this.$route.name,
      listQuery: {
        search: '',
        page: 1,
        lotid: '',
        send_user: '',
        buy_user: ''
      },
      list: [],
      total: 0,
      listLoading: true,
      userLoading: false,
      sendUsers: [],
      buyUsers: [],
      lots: [],
      lotLoading: false,
      taxRate: '',
      checkList: [],
      printLoading: false,
      printData: {
        type: '',
        title: '',
        info: {},
        list: []
      },
      dialogPrintVisible: false,
      outLoading: false,
      dialogSettleVisible: false,
      settleData: [],
      settleLoading: false,
      orderForm: {
        other_fee: '',
        bankname: '',
        bankcard: '',
        address: '',
        remark: ''
      }
    }
  },
  computed: {
    roles () {
      return this.$store.getters.roles
    },
    emptyText () {
      const routeName = this.$route.name
      var res = '暂无拍品'
      switch (true) {
        case routeName === 'SettleBuy':
          res = '暂无待付款的拍品'
          break
        case routeName === 'SettleSend':
          res = '暂无待结算的拍品'
          break
        case routeName === 'GoodsOut':
          res = '暂无待提货的拍品'
          break
      }
      return res
    },
    feeRate () {
      var res = {
        send: 0,
        buy: 0
      }
      if (this.listQuery.buy_user) {
        const index = this.buyUsers.findIndex(el => el.id === this.listQuery.buy_user)
        res.buy = this.buyUsers[index].fee_rate || 0
      }
      if (this.listQuery.send_user) {
        const index = this.sendUsers.findIndex(el => el.id === this.listQuery.send_user)
        res.send = this.sendUsers[index].fee_rate || 0
      }
      return res
    },
    cataFee () {
      if (this.listQuery.send_user) {
        const index = this.sendUsers.findIndex(el => el.id === this.listQuery.send_user)
        return this.sendUsers[index].catafee || 0
      } else {
        return 0
      }
    },
    currUser () {
      if (this.routeName === 'SettleBuy') {
        const index = this.buyUsers.findIndex(el => el.id === this.listQuery.buy_user)
        return this.buyUsers[index]
      } else if (this.routeName === 'SettleSend' || this.routeName === 'InReceipt') {
        const index = this.sendUsers.findIndex(el => el.id === this.listQuery.send_user)
        return this.sendUsers[index]
      } else {
        return null
      }
    },
    // 其他费用+合计
    orderTotalFee () {
      const sumarr = this.settleData.map(el => el.sum)
      var sum = 0
      if (sumarr.length > 0) {
        sum = sumarr.reduce(function (prev, curr, idx, arr) {
          return Number(prev) + Number(curr)
        })
        if (this.orderForm.other_fee >= 0) {
          sum += Number(this.orderForm.other_fee)
        } else {
          sum -= Math.abs(this.orderForm.other_fee)
        }
      } else {
        sum = this.orderForm.other_fee
      }
      return sum
    }
  },
  created () {
    this.fetchUsers()
    this.fetchLots()
    this.fetchTax()
  },
  methods: {
    fetchData () {
      this.listLoading = true
      getGoods(this.listQuery).then(res => {
        this.list = res.data.list
        this.total = res.data.total
        this.lotName = res.data.lot_name
        this.listLoading = false
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    fetchUsers () {
      this.userLoading = true
      getAllUsers().then(res => {
        this.sendUsers = res.data.send
        this.buyUsers = res.data.buy
        this.userLoading = false
      }).catch(err => {
        console.log(err)
        this.userLoading = false
      })
    },
    fetchLots () {
      this.lotLoading = true
      getAllLots().then(res => {
        this.lots = res.data
        this.lotLoading = false
        this.listQuery.lotid = this.lots[0].id
      }).catch(err => {
        console.log(err)
        this.lotLoading = false
      })
    },
    fetchTax () {
      getTaxRate().then(res => {
        this.taxRate = res.data
      }).catch(err => {
        console.log(err)
        this.taxRate = 0
      })
    },
    handleFilter (fromBtn) {
      if (fromBtn) {
        if (!this.listQuery.lotid || !(this.listQuery.send_user || this.listQuery.buy_user)) {
          this.$message.info('请将查询条件补充完整')
        }
      }
      this.listQuery.page = 1
      this.fetchData()
    },
    handleCheckChange (arr) {
      this.checkList = arr
    },
    handleOneKeyOut () {
      this.$confirm('确认要进行一键提货吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.outLoading = true
        const idArr = this.checkList.map(el => el.id)
        setGoodsStateMulti({ ids: idArr, state: 5 }).then(res => {
          this.outLoading = false
          this.fetchData()
          this.$message.success('一键提货操作成功！')
        }).catch(err => {
          console.log(err)
          this.outLoading = false
        })
      }).catch(() => {})
    },
    // 买家付款 卖家结算
    handleCreateOrder (data) {
      var goodsList = []
      if (data.goods) {
        goodsList = JSON.parse(JSON.stringify(data.goods))
      } else {
        goodsList = JSON.parse(JSON.stringify(this.checkList))
      }
      this.settleData = goodsList.map(el => {
        var res = {
          id: el.id,
          number: el.number,
          final_price: el.final_price,
          fee_rate: this.feeRate[data.type],
          fee: parseInt(el.final_price * this.feeRate[data.type]),
          tax_rate: this.taxRate,
          tax: parseInt(el.final_price * this.feeRate[data.type] * this.taxRate),
          postage: el.postage
        }
        if (data.type === 'buy') {
          res.sum = res.final_price + res.fee + res.tax + res.postage
        } else {
          res.catafee = this.cataFee
          res.sum = res.final_price - res.fee - res.tax - this.cataFee
        }
        return res
      })
      this.orderForm = {
        other_fee: '',
        bankname: this.currUser.bankname,
        bankcard: this.currUser.bankcard,
        address: this.currUser.address,
        remark: ''
      }
      this.dialogSettleVisible = true
    },
    submitOrder () {
      this.settleLoading = true
      const type = this.routeName === 'SettleBuy' ? 'buy' : 'send'
      const printName = type === 'buy' ? '付款提货单' : '出品人结算单'
      const { remark, bankname, bankcard, address, other_fee } = this.orderForm
      const data = {
        ids: this.settleData.map(el => el.id),
        type: type,
        fee_rate: this.feeRate[type],
        tax_rate: this.taxRate,
        other_fee,
        remark,
        bankname,
        bankcard,
        address
      }
      if (type === 'send') {
        data.catafee = this.cataFee
      }
      createOrder(data).then(res => {
        this.settleLoading = false
        this.fetchData()
        this.dialogSettleVisible = false
        this.$confirm(`订单创建成功！是否立即打印${printName}？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '关闭',
          type: 'success'
        }).then(() => {
          this.$router.push(`/order/${type}?order=${res.data}&print=1`)
        }).catch(() => {})
      }).catch(err => {
        console.log(err)
        this.settleLoading = false
      })
    },

    toThousands,

    handleOneKeyPrint () {
      if (this.routeName === 'SettleBuy') {
        this.printData.title = '付款提货单'
        this.printData.type = 'settle_buy'
      } else if (this.routeName === 'SettleSend') {
        this.printData.title = '出品人结算单'
        this.printData.type = 'settle_send'
      } else {
        this.printData.title = '拍品入库单'
        this.printData.type = 'editor'
      }
      this.printData.info.user_name = this.currUser.name
      this.printData.list = this.checkList.map(el => {
        var res = {
          number: el.number,
          name: el.name,
          fee_rate: this.currUser.fee_rate,
          tax_rate: this.taxRate
        }
        if (this.routeName === 'SettleBuy') {
          res.final_price = el.final_price
          res.fee = parseInt(el.final_price * this.currUser.fee_rate)
          res.tax = parseInt(el.final_price * this.currUser.fee_rate * this.taxRate)
          res.sum = res.final_price + res.fee + res.tax + res.postage
        } else if (this.routeName === 'SettleSend') {
          res.final_price = el.final_price
          res.fee = parseInt(el.final_price * this.currUser.fee_rate)
          res.tax = parseInt(el.final_price * this.currUser.fee_rate * this.taxRate)
          res.sum = res.final_price - res.fee - res.tax - this.currUser.catafee
        } else {
          res.catafee = this.currUser.catafee
        }
        return res
      })
      this.dialogPrintVisible = true
    },
    doPrint () {
      const style = '@page { margin:0 } '
      Print({
        printable: 'printContent',
        type: 'html',
        style: style,
        // 继承原来的所有样式
        targetStyles: ['*']
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-container {
  &>.el-select {
    width: 250px;
  }
}
.pagination-container {
  margin-top: 15px;
}
.print-dialog {
  /deep/.el-dialog__body {
    padding: 0 calc(50vw - 405px);
    height: calc(100vh - 120px);
    overflow: scroll;
  }
}
</style>
<style lang="scss">
.check-list {
  /deep/.el-table__footer {
    tbody tr {
      td:last-of-type {
        color: #c20625;
        font-weight: bold;
      }
    }
  }
}
.el-dialog {
  .el-input.is-disabled {
    .el-input__inner {
      color: #333;
    }
  }
}
#printContent {
  width: 790px;
  padding: 20px;
  margin: auto;
  .el-table--medium td {
    padding: 8px 0;
    font-size: 13px;
    .cell {
      padding: 0 4px;
    }
  }
}
</style>
